package com.lin.manager.common.utils;


import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.BeanWrapperImpl;

import java.util.ArrayList;
import java.util.List;

/**
 * @作者: 林江
 * @创建时间: 2023/11/18
 * @功能:
 */
public class TreeUtil {

    private String idName = "id";
    private String parentIdName = "parentId";
    private String childName = "children";

    public static TreeHelperBuilder builder() {
        return new TreeHelperBuilder();
    }

    public static class TreeHelperBuilder {
        TreeUtil treeUtil = new TreeUtil();

        public TreeHelperBuilder idName(String idName) {
            treeUtil.idName = idName;
            return this;
        }

        public TreeHelperBuilder parentIdName(String parentIdName) {
            treeUtil.parentIdName = parentIdName;
            return this;
        }

        public TreeHelperBuilder childName(String childName) {
            treeUtil.childName = childName;
            return this;
        }

        public TreeUtil build() {
            return treeUtil;
        }
    }

    public <T, C> List<C> tree(List<T> data, Object pId, Class<C> clazz) {
        List result = new ArrayList();
        for (T datum : data) {
            Object parentIdV = BeanUtil.getFieldValue(datum, parentIdName);
            if (parentIdV == pId || parentIdV.toString().equals(pId.toString())) {
                BeanWrapperImpl wrapper = new BeanWrapperImpl(clazz);
                Object instance = wrapper.getWrappedInstance();
                BeanUtil.copyProperties(datum, instance);

                List list = tree(data, BeanUtil.getFieldValue(datum, idName), clazz);
                BeanUtil.setFieldValue(instance, childName, list);
                result.add(instance);
            }
        }
        return result;
    }
}
